<template>
  <el-dialog
    v-model="visible"
    :show-close="false"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="90%"
    top="8vh"
    class="component-shop-edit-category header-no-padding"
    @close="closePopup"
  >
    <div class="">
      <div class="popup">
        <div class="title">
          <div class="text">
            <span class="stress">*</span>{{ $t('shopProcess.editSigningCategory') }}
          </div>
          <div class="tips">
            {{ $t('shopProcess.preSigned') }}
            <span class="bold">{{ totalCount }}</span>
            {{ $t('shopProcess.piece') }}{{ $t('shopProcess.category') }}，{{ $t('shopProcess.mostAdd') }}
            <span class="bold">200</span>
            {{ $t('shopProcess.piece') }}{{ $t('shopProcess.category') }}
          </div>
          <div
            class="close-btn"
            @click="closePopup"
          >
            <el-icon><Close /></el-icon>
          </div>
        </div>

        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-form
            ref="searchFormRef"
            :inline="true"
            :model="searchForm"
            label-width="auto"
            @submit.prevent
          >
            <div class="input-row margin-bottom-none">
              <el-form-item
                prop="categoryId"
                :label="$t('publics.category')"
              >
                <el-cascader
                  ref="cascaderAddrRef"
                  v-model="selectedPlatformCategories"
                  filterable
                  :options="categoryList"
                  :props="platformCategoriesTreeProps"
                  style="width:100%"
                  clearable
                  :placeholder="$t('tip.select')"
                  change-on-select
                  :show-all-levels="false"
                  @change="handlePlatformCategoryChange"
                />
              </el-form-item>
              <el-form-item>
                <div
                  class="default-btn primary-btn"
                  @click="onSearch"
                >
                  {{ $t('product.search') }}
                </div>
                <div
                  class="default-btn"
                  @click="onResetSearch()"
                >
                  {{ $t('product.reset') }}
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <div class="main-container content">
          <!-- 表格 -->
          <div
            ref="tableBoxRef"
            class="table-con right-box table-box"
          >
            <el-table
              :data="signCategories"
              header-cell-class-name="table-header"
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                :label="$t('shopProcess.categoryName')"
              />
              <el-table-column
                prop="parentName"
                :label="$t('shopProcess.parentCategoryName')"
              />
              <el-table-column
                prop="platformRate"
                :label="$t('shopProcess.categoryRate')"
              >
                <template #default="{ row }">
                  <span v-if="row.platformRate || row.platformRate === 0">{{ row.platformRate }} %</span>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="customizeRate"
                :label="$t('shopProcess.customRate')"
              >
                <template #default="scope">
                  <div class="custom-rate">
                    <el-input
                      v-model="scope.row.customizeRate"
                      :min="0"
                      :max="99.9999"
                      :precision="4"
                      placeholder="0~99.9999"
                      style="width: 80%;"
                      @blur="checkCustomizeRateInt(scope)"
                      @keydown="channelInputLimit"
                    />%
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="qualifications"
                :label="$t('shopProcess.categoryQualifications')"
              >
                <template #default="scope">
                  <div
                    v-if="scope.row.imgs.length"
                    class="business-qual"
                  >
                    <el-image
                      v-for="(img,index) in scope.row.imgs"
                      :key="index"
                      class="rotating-img"
                      :src="checkFileUrl(img)"
                      preview-teleported
                      :preview-src-list="checkFileUrl(scope.row.imgs)"
                    />
                  </div>
                  <span v-else>--</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="categoryStatus"
                :label="$t('shopProcess.categoryStatus')"
              >
                <template #default="scope">
                  <div
                    v-if="scope.row.categoryStatus === 1"
                    class="tag-txt"
                  >
                    {{ $t('publics.normal') }}
                  </div>
                  <div
                    v-if="scope.row.categoryStatus === 0"
                    class="tag-txt red-tag-txt"
                  >
                    {{ $t('publics.LowerShelf') }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="address"
                :label="$t('remindPop.operation')"
                width="100px"
                align="center"
              >
                <template #default="scope">
                  <div
                    class="default-btn text-btn"
                    @click="deleteSelectedCategory(scope)"
                  >
                    {{ $t('remindPop.delete') }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="pagination">
            <!-- 分页 -->
            <el-pagination
              :current-page="page.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.total"
              @size-change="onPageSizeChange"
              @current-change="onPageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const platformCategoriesTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})

let shopId = 0
const visible = ref(false)
const init = (shopIdPar) => {
  shopId = shopIdPar
  visible.value = true
  getSignCategoryList()
  getPlatformCategory()
}

let signList = []
const signCategories = ref([])
const totalCount = ref(null) // 签约总数量
const searchForm = ref({}) // 搜索
/**
 * 获取已签约类目列表
 */
const getSignCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/pageSigningInfo'),
    method: 'get',
    params: http.adornParams(Object.assign({
      shopId,
      current: page.currentPage,
      size: page.pageSize,
      status: 1 // 签约状态：1：已通过 0待审核 -1未通过
    }, searchForm.value))
  }).then(({ data }) => {
    signList = JSON.parse(JSON.stringify(data.records))
    signCategories.value = handleImgData(data.records)
    page.total = data.total
    page.currentPage = data.current
    if (totalCount.value === null) {
      totalCount.value = data.total
    }
    if (page.currentPage > data.pages) {
      page.currentPage = data.pages
      getSignCategoryList()
    }
  })
}

/**
 * 监听平台分类选择变化
 */
const handlePlatformCategoryChange = (val) => {
  searchForm.value.primaryCategoryId = undefined
  searchForm.value.secondaryCategoryId = undefined
  searchForm.value.categoryId = undefined
  if (val.length === 1) { // 长度为1，表明当前选择的是一级分类（点击了一级分类）
    searchForm.value.primaryCategoryId = val[0] // 平台一级分类id
  } else if (val.length === 2) { // 长度为2，表明当前选择的是二级分类（点击了二级分类）
    searchForm.value.secondaryCategoryId = val[1] // 平台二级分类id
  } else if (val.length === 3) { // 长度为3，表明当前选择的是三级分类（点击了三级分类）
    searchForm.value.categoryId = val[2] // 平台三级分类id
  }
}

const handleImgData = (dataList) => {
  dataList.forEach(item => {
    item.imgs = item.qualifications ? item.qualifications.split(',') : []
  })
  return dataList
}

const categoryList = ref([])
/**
 * 获取平台分类列表，并转换成树形结构
 */
const getPlatformCategory = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      maxGrade: 2,
      status: 1
    })
  }).then(({ data }) => {
    let categorgTreeData = treeDataTranslate(data, 'categoryId', 'parentId')
    // 过滤没有下级分类的类目
    categorgTreeData = removeNotThirdCategoryItem(categorgTreeData)
    categoryList.value = categorgTreeData
  })
}

/**
 * 去除没有三级分类的类目
 */
const removeNotThirdCategoryItem = (treeData) => {
  const firstCategory = treeData
  for (let i = 0, index = 0; i < firstCategory.length; i++) {
    if (firstCategory[index].grade !== 2) {
      if (firstCategory[index].children) {
        const secondCategory = firstCategory[index].children
        firstCategory[index].children = removeNotThirdCategoryItem(secondCategory)
      } else {
        firstCategory.splice(index, 1)
        // 当前位置的元素已经被删除，当前位置索引不用++
        continue
      }
    }
    index++
  }
  return firstCategory
}

/**
 * 自定义扣率输入框判断
 */
const checkCustomizeRateInt = (scope) => {
  const { row, $index } = scope
  const orgCustomizeRate = JSON.parse(JSON.stringify(signList[$index].customizeRate))
  let customizeRate = parseFloat(row.customizeRate)
  let verification = true
  if (customizeRate === 0) {
    signCategories.value[$index].customizeRate = 0
    customizeRate = 0
  }
  // 如果当前项原本无自定义扣率，失焦时输入框内容为空，则终止
  if ((!orgCustomizeRate && orgCustomizeRate !== 0) && (!customizeRate && customizeRate !== 0)) {
    return
  }
  if (customizeRate) {
    // 0~99.9999
    const reg = /^(([1-9]{0,1}?\d{1}?)|(0{1}))(\.\d{0,4})?$/
    if (!reg.test(customizeRate)) {
      signCategories.value[$index].customizeRate = orgCustomizeRate || ''
      ElMessage({
        message: $t('shopProcess.customizeRateErrorTips'),
        type: 'error',
        duration: 2000
      })
      verification = false
    }
  }
  if (verification) {
    changeCustomizeRateInt(scope)
  }
}

const channelInputLimit = (e) => {
  const key = e.key
  // 不允许输入'-'
  if (key === '-' || key === '+') {
    e.returnValue = false
    return false
  }
  return true
}

/**
 * 修改扣率
 */
const changeCustomizeRateInt = (scope) => {
  const param = {
    categoryId: scope.row.categoryId,
    rate: scope.row.customizeRate,
    shopId
  }
  http({
    url: http.adornUrl('/platform/categoryShop/updateRate'),
    method: 'put',
    params: param
  }).then(() => {
    ElMessage({
      message: $t('shopProcess.customizeRateEditSuccess'),
      type: 'success',
      duration: 1000,
      onClose: () => {}
    })
    signList = JSON.parse(JSON.stringify(signCategories.value))
  })
}

/**
 * 删除已选分类
 */
const deleteSelectedCategory = (scope) => {
  ElMessageBox.confirm($t('shopProcess.defineDeleteSigning') + '[' + scope.row.name + ']?', $t('remindPop.remind'), {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/platform/categoryShop'),
      method: 'DELETE',
      params: http.adornParams({
        categoryId: scope.row.categoryId,
        shopId
      })
    }).then(() => {
      ElMessage({
        message: $t('shopProcess.deleteSigningCategorySuccess'),
        type: 'success',
        duration: 1000,
        onClose: () => {}
      })
      getSignCategoryList()
      totalCount.value--
    })
  }).catch(() => {})
}

const emit = defineEmits(['closePopup'])
/**
 * 关闭弹窗
 */
const closePopup = () => {
  emit('closePopup', 'category')
}

const onSearch = () => {
  page.currentPage = 1
  getSignCategoryList()
}

const searchFormRef = ref(null)
const selectedPlatformCategories = ref([])
/**
 * 重置表单
 */
const onResetSearch = () => {
  searchFormRef.value.resetFields()
  selectedPlatformCategories.value = []
  searchForm.value = {}
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getSignCategoryList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getSignCategoryList()
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
@use "index";
</style>
